package com.ly.cloud.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.ly.cloud.entity.TemporaryStudentPo;
import com.ly.cloud.exception.CloudException;
import com.ly.cloud.mapper.TemporaryStudentMapper;
import com.ly.cloud.service.TemporaryStudentService;
import com.ly.cloud.utils.ExcelUtils;
import com.ly.cloud.vo.ClassStuVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description:
 * @Author: pengshiqng
 * @Date: Create in 2018/12/20
 */

@Service
public class TemporaryStudentServiceImpl implements TemporaryStudentService {

    /** 模板 */
    final String[] ARR_TEMP = new String[]{
            "考生号(必填)","学生姓名(必填)","英文姓名","姓名拼音","曾用名","性别(必填)","民族(必填)","政治面貌","籍贯","国籍地区",
            "身份证件类型(必填)","身份证件号(必填)","出生日期(yyyy-MM-dd)(必填)","血型","校区(必填)","所在年级(必填)","所在学院(必填)","所在系部","年级专业方向(必填)","当前学籍状态(必填)",
            "学制(必填)","是否在校(必填)","是否在籍(必填)","学习形式(必填)","培养层次(必填)","培养方式","入学方式(必填)","入学日期(yyyy-MM-dd)(必填)","考生类别","生源地(必填)",
            "毕业中学名称","入学总分","联系电话","电子信箱","QQ/微信号","邮政编码","家庭电话","家庭地址","通讯地址"
    };

    @Autowired
    private TemporaryStudentMapper temporaryStudentMapper ;


    // 分页 + 条件 查询 原型图左边
    @Override
    public Page<Map<String, String>> selectPageLeft(Page<Map<String, String>> page, String grade, String profe, String name) {
        try {
            return page.setRecords(temporaryStudentMapper.selectPageLeft(page, grade, profe, name));
        } catch (Exception e) {
            throw new CloudException("查询异常，请重试!", e);
        }
    }

    // 分页 + 条件 查询 原型图右边
    @Override
    public Page<Map<String, String>> selectPageRight(Page<Map<String, String>> page, String grade, String profe, String college) {
        try {
            return page.setRecords(temporaryStudentMapper.selectPageRight(page, grade, profe, college));
        } catch (Exception e) {
            throw new CloudException("查询异常，请重试!", e);
        }
    }

    //删除
    @Override
    public int deleteById(String id) {
       try {
           return temporaryStudentMapper.deleteById(id);
       } catch (Exception e){
           e.printStackTrace();
           throw new CloudException("删除失败!", e);
       }
    }

    //批量删除
    @Override
    public int deleteByIds(List<String> ids) {
        try {
            return temporaryStudentMapper.deleteBatchIds(ids);
        } catch (Exception e){
            e.printStackTrace();
            throw new CloudException("批量删除失败!", e);
        }
    }

    /**
    * @Description: 导入
    * @Author: pengshiqing
    * @CreateDate: 2018/12/24
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(MultipartFile file) {
        try {
            List<String[]> list = ExcelUtils.readExcel(file);
            if (CollectionUtils.isNotEmpty(list)){
                //读取模板第一行第一列（标题）是否是学生临时信息导入
                if (ObjectUtils.notEqual("学生临时信息导入",list.get(0)[0])){
                    throw new CloudException("模板标题不对，应为【学生临时信息导入】，请选择正确的模板!");
                }
                //判断表头
                String[] arr_top = list.get(1) ;
                for (int i = 0 ; i < arr_top.length; i++) {
                    if ( ObjectUtils.notEqual(ARR_TEMP[i],arr_top[i]) ){
                        throw new CloudException("模板不对,第"+(i+1)+"列当前是【"+arr_top[i]+"】,实际应为【"+ ARR_TEMP[i]+"】,请选择正确的模板!");
                    }
                }
                TemporaryStudentPo po = new TemporaryStudentPo();
                po.setCjsj(new Date());
                //刚导入的数据都没有转入正式库
                po.setSfzr("0");
                //遍历excel每一条数据,从第三列(i=2)开始读取，excel第一、第二列是表头
                for (int i = 2 ; i< list.size() ; i++){
                    String[] arr = list.get(i) ;
                    po.setXsid(UUID.randomUUID().toString().replace("-",""));
                    po.setKsh(checkedStr(arr[0], arr[0] , 0));
                    po.setXm(checkedStr(arr[1],arr[0],1));
                    po.setYwmc(arr[2]);
                    po.setXmpy(arr[3]);
                    po.setCym(arr[4]);
                    po.setXbm(checkedStr(arr[5],arr[0],5));
                    po.setMzm(checkedStr(arr[6],arr[0],6));
                    po.setZzmm(arr[7]);
                    po.setJg(arr[8]);
                    po.setGj(arr[9]);
                    po.setZjlx(checkedStr(arr[10],arr[0],10));
                    po.setZjh(checkedStr(arr[11],arr[0],11));
                    po.setCsrq(arr[12]);
                    po.setXxm(arr[13]);
                    po.setXqh(checkedStr(arr[14],arr[0],14));
                    po.setNj(checkedStr(arr[15],arr[0],15));
                    po.setXy(checkedStr(arr[16],arr[0],16));
                    po.setXi(arr[17]);
                    po.setZyfx(checkedStr(arr[18],arr[0],18));
                    po.setXjzt(checkedStr(arr[19],arr[0],19));
                    //学制
                    BigDecimal xz = null ;
                    try {
                        xz = new BigDecimal(checkedStr(arr[20],arr[0],20));
                    } catch (NumberFormatException e){
                        throw new CloudException("导入失败!,学号为"+arr[0]+","+ARR_TEMP[20]+"格式不正确", e);
                    }
                    po.setXz(xz);
                    po.setZxzt(checkedStr(arr[21],arr[0],21));
                    po.setSfzj(checkedStr(arr[22],arr[0],22));
                    po.setXxxs(checkedStr(arr[23],arr[0],23));
                    po.setPycc(checkedStr(arr[24],arr[0],24));
                    po.setPyfs(arr[26]);
                    po.setRxfs(checkedStr(arr[26],arr[0],26));
                    po.setRxrq(checkedStr(arr[27],arr[0],27));
                    po.setKslb(arr[28]);
                    po.setSyd(checkedStr(arr[29],arr[0],29));
                    po.setByzx(arr[30]);
                    po.setRxzf(arr[31]);
                    po.setLxdh(arr[32]);
                    po.setDzyj(arr[33]);
                    po.setWxh(arr[34]);
                    po.setYzbm(arr[35]);
                    po.setJtdh(arr[36]);
                    po.setJtdz(arr[37]);
                    po.setTxdz(arr[38]);
                    temporaryStudentMapper.insert(po);
                }
            }
        } catch (CloudException e){
            e.printStackTrace();
            throw new CloudException(e.getMessage(), e);
        }catch (Exception e){
            e.printStackTrace();
            throw new CloudException("导入失败!", e);
        }
    }


    /**
    * @Description: 分班
    * @Author: pengshiqing
    * @CreateDate: 2018/12/24
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int sepClass(String bjdm, List<String> list) {
        try {
            temporaryStudentMapper.sepClass(bjdm, list);
            //返回操作成功数，也就是list的大小
            return list.size();
        } catch (Exception e){
            e.printStackTrace();
            throw new CloudException("分班失败!", e);
        }
    }

    /**
     * @Description: 选中班级取消分班
     * @Author: pengshiqing
     * @CreateDate: 2018/12/24
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelSepClassByClassId(List<String> list) {
        int count = 0 ;
        try {
            //遍历所有的班级
            for (String classId : list){
                //查询该班级中没有转入正式库的学生xsid
                List<String> xsids = temporaryStudentMapper.findAllNotInFL(classId);
                if (CollectionUtils.isEmpty(xsids)){
                    continue;
                }
                //取消分班
                count = count + temporaryStudentMapper.cancelSepClass(xsids);
            }
            //返回取消分班的班级,只是取消该班级没有转入正式库的学生，也就是list的大小
            return count;
        } catch (Exception e){
            e.printStackTrace();
            throw new CloudException("取消分班失败!", e);
        }
    }


    /**
     * @Description: 根据xsid批量取消分班
     * @Author: pengshiqing
     * @CreateDate: 2018/12/25
     */
    @Override
    public int cancelSepClaByXsid(List<String> list) {
        try {
            //取消分班 设置学号为null和班级id为空
            return temporaryStudentMapper.cancelSepClass(list) ;
        } catch (Exception e){
            e.printStackTrace();
            throw new CloudException("取消失败!", e);
        }
    }


    /**
    * @Description: 编学号
    * @Author: pengshiqing
    * @CreateDate: 2018/12/24
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editStudentId(String type ,List<String> list) {
        try {
            //计数 ,成功编学号的学生
            int count = 0 ;
            for (String bjdm : list){
                //学号流水号
                int num = 1 ;
                //查询该班级下面的所有学号为空的学生(学生id，班级)   type =1:根据姓名排序，tpye=2,根据考生号排序
                List<String> idIsNull = temporaryStudentMapper.findIdIsNull(type , bjdm);
                //查询临时表该班级下面的所有学号不为空的学生
                List<String> xhNotNullInLs = temporaryStudentMapper.findIdNotNull(bjdm);
                //查询正式表该班级的所有学号
                List<String> xhNotNullInZs = temporaryStudentMapper.findAllIdInZsb(bjdm);
                //循环学号为空的学生，设置学号，（班级号+三位数的流水号，01,02,03...),如果设置的学号存在，则跳过次学号
                for (String xsid : idIsNull){
                    String xh = "";
                    do {
                        xh = bjdm + (num <10?("0"+num):num) ;
                        num ++ ;
                    } while ( xhNotNullInLs.contains(xh) || xhNotNullInZs.contains(xh));
                    //更新到学生临时表
                    temporaryStudentMapper.updateStudentXh(xsid,xh);
                    count ++ ;
                }
            }
            return count;
        } catch (Exception e){
            e.printStackTrace();
            throw new CloudException("编学号失败!", e);
        }
    }

    /**
    * @Description: 转入正式库
    * @Author: pengshiqing
    * @CreateDate: 2018/12/25
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int intoFormalLibrary(List<String> list) {
        String bjid = null ;
        try {
            int count = 0 ;
            //遍历班级，查询该班级没有转入正式库并且没有编学号的学生
            for (String classId : list){
                bjid = classId ;
                List<String> xsids = temporaryStudentMapper.findAllNotInFLAndXhIsNull(classId);
                count = count + xsids.size() ;
                if (xsids.size() > 0){
                    //转入正式库
                    temporaryStudentMapper.intoFormalLibrary(xsids);
                    //更新状态
                    temporaryStudentMapper.updateStateUpSfzr(xsids);
                }
            }
            return count ;
        } catch (Exception e){
            e.printStackTrace();
            throw new CloudException("转入正式库失败!,班级代码:"+ bjid +"的学生存在学号冲突，请重新给改班级编学号!", e);
        }
    }

    /**
    * @Description: 根据班级代码查询该班级所有的学生
    * @Author: pengshiqing
    * @CreateDate: 2018/12/25
    */
    @Override
    public Page<ClassStuVo> findAllStuByClassId(Page<ClassStuVo> page, String classId, String ksh , String name) {
        try {
            return page.setRecords(temporaryStudentMapper.findAllStuByClassId(page, classId, ksh, name));
        } catch (Exception e){
            e.printStackTrace();
            throw new CloudException("查询失败!", e);
        }
    }


    /**
     * 验证表格数据是否为空，如果为空，直接抛异常
     */
    private String checkedStr(String str,String ksh ,int column){
        if (StringUtils.isBlank(ksh)){
            throw new CloudException("导入失败!,考生号不能为空");
        }
        if (StringUtils.isBlank(str)){
            throw new CloudException("导入失败!,考生号为:"+ ksh +" 的学生第" +(column+1) +"列【"+ ARR_TEMP[column] +"】不能为空");
        }
        return str ;
    }


}
